package com.example.blemulticondemo.utils;

import com.example.blemulticondemo.event.CommonEvent;
import com.example.blemulticondemo.event.EventCode;

import org.greenrobot.eventbus.EventBus;

import java.util.Timer;
import java.util.TimerTask;

/**
 * @author linvisf
 * @date 2023/1/18
 */
public class SendTimer {
    private static SendTimer sendTimer;
    private Timer mTimerSend;
    private TimerTask taskSend;
    private int TimeCount = 0;
    private int Time_Send = 4000;

    public SendTimer() {
    }

    public static SendTimer getInstance() {
        if (sendTimer == null) {
            sendTimer = new SendTimer();
        }

        return sendTimer;
    }

    public void setSendTimeOutStart(final MyCallBack callBack) {
        try {
            this.setSendTimeOutCancel();
            this.TimeCount = 0;
            this.mTimerSend = new Timer();
            this.taskSend = new TimerTask() {
                public void run() {
                    callBack.sendCallBack();
                    SendTimer.this.TimeCount++;
                    if (SendTimer.this.TimeCount >= 3) {
                        EventBus.getDefault().post(new CommonEvent(EventCode.SERIAL_THIRD_TIMEOUT));
                        if (SendTimer.this.mTimerSend != null) {
                            SendTimer.this.mTimerSend.cancel();
                        }

                        if (SendTimer.this.taskSend != null) {
                            SendTimer.this.taskSend.cancel();
                        }
                    }

                }
            };
            this.mTimerSend.schedule(this.taskSend, 0L, (long)this.Time_Send);
        } catch (Exception var3) {
            var3.printStackTrace();
            callBack.sendCallBack();
        }

    }

    public void setSendTimeOutCancel() {
        if (this.mTimerSend != null) {
            this.mTimerSend.cancel();
            this.mTimerSend = null;
        }

        if (this.taskSend != null) {
            this.taskSend.cancel();
            this.taskSend = null;
        }

    }

    interface MyCallBack {
        void sendCallBack();
    }
}
